<!--
 * @Author: LAB
 * @Date: 2021-05-18 11:40:44
 * @Description: 自制药品列表
 * @FilePath: \client-app\src\views\drug\components\drug-made.vue
-->
<template>
  <div>
    <CreateDrugMade
      v-model:value="isCreateDrug"
      @success="addSuccess"
      :drugId="drugId"
      :drugType="drugType"
      :drugSchemeId="drugSchemeId"
      :specificationId="specificationId"
    />
    <DataGrid
      v-bind="DataGridSetting"
      :data-source="items"
      @context-menu-preparing="setRightMenu"
      :remote-operations="false"
      :selectedRowKeys="selectedRowKeys"
      @selectionChanged="selectionChanged"
    >
      <template #uploadImg="{ data: cellInfo }">
        <imageUpload
          :limit="1"
          :files="cellInfo.Value"
          @change="cellInfo.setValue"
        />
      </template>
      <template #headerTemplate="{ data: column }">
        <div class="header-input" style="width: 100%">
          <div
            style="width: 60%"
            v-if="!isEditHeader[column.columnIndex]"
            @dblclick="isEditHeader[column.columnIndex] = true"
            @click.stop="none"
          >
            {{ getHeaderTitle(column) }}
          </div>
          <DxTextBox
            @keydown.stop="none"
            @click.stop="none"
            v-else
            :placeholder="column.column.caption"
            :Value="getHeaderTitle(column)"
            @focusOut="
              (event) => setHeader(event, column.column, column.columnIndex)
            "
            @enterKey="
              (event) => setHeader(event, column.column, column.columnIndex)
            "
          />
        </div>
      </template>
    </DataGrid>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import ImageUpload from "@/components/image-upload.vue";
import { ApiTool } from "@/api/api-tool";
import { Inject, Watch } from "vue-property-decorator";
import { OutPutDrugInfo } from "@/api/api_dictionaryclient";
import notify from "devextreme/ui/notify";
import { DxHtmlEditor } from "devextreme-vue/html-editor";
import Pagination from "@/framework/elementui/pagination.vue";
import DxTabs from "devextreme-vue/tabs";
import {
  DxDataGrid,
  DxColumn,
  DxPaging,
  DxEditing,
  DxLookup,
  DxForm,
  DxSearchPanel,
  DxExport,
  DxSorting,
  DxPager,
  DxRequiredRule,
  DxEmailRule,
  DxPatternRule,
  DxAsyncRule,
  DxSelection,
} from "devextreme-vue/data-grid";
import DataGrid from "@/framework/components/data-grid/data-grid.vue";
import { DxPopup } from "devextreme-vue/popup";
import DxButton from "devextreme-vue/button";
import { SearchByURL } from "@/utils/search-byurl";
import { RouteLocation } from "vue-router";
import { PageInfo, Tool } from "@/utils/tool";
import { ApiExceptionShow } from "@/utils/api-exception-show";
import DxTextBox from "devextreme-vue/text-box";
import ThemeSwitch from "@/framework/theme-switch/theme-switch";
import { DictionaryFieldOutput } from "@/api/api_solutionclient";
import { CatalogClient } from "@/api/api_catalogclient";
import { ViewTool } from "@/framework/utils/view-tool";
import DxSortable from "devextreme-vue/sortable";
import LoadElement from "@/framework/utils/load-element";
import Tree from "@/framework/components/tree/tree.vue";
import { RightContextI } from "@/framework/components/right-menu/right-menu.vue";
// import CreateMiddle from "./create-middle.vue";
import { DrugClient } from "@/api/api_drugclient";
import DrugData from "@/data-source/drug";
import CreateDrugMade from "./create-drug-made.vue";
import { dxDataGridOptions } from "devextreme/ui/data_grid";
import {
  AgreementDrugClient,
  OutputAgreementDrugModel,
} from "@/api/api_agreementdrugclient";
import { SelfMadeDrugClient } from "@/api/api_selfmadedrugclient";

const componentInfo = {
  title: "药品信息",
};
let formData: any = {};
let self: any;
const keyExpr = "compositionSpecificationId";
// 配置类型 1：金融中心产品轮播图 2：金融产品类型配置 3：还款方式 4 协议配置
const getDataGridSetting = function () {
  return {
    height: "calc(33vh - 90px)",
    width: "calc(100vw - 355px)",
    showBorders: true,
    showColumnLines: false,
    showRowLines: false,
    hoverStateEnabled: true,
    allowColumnResizing: true,
    allowColumnReordering: true,
    remoteOperations: false,
    sorting: {
      mode: "single",
    },
    selection: {
      mode: "single",
    },
    keyExpr,
    rowAlternationEnabled: true,
    noDataText: "该药品暂无自制药品信息，请右键新增",
    onToolbarPreparing: (e) => {
      let toolbarItems = e.toolbarOptions.items;
      toolbarItems.length = 0;
    },
    columns: [
      {
        caption: "id",
        dataField: "compositionSpecificationId",
        allowEditing: false,
        allowSorting: false,
      },
      {
        caption: "药品名称 ",
        dataField: "compositionSpecificationName",
      },
      {
        caption: "规格",
        dataField: "specificationName",
      },
      {
        caption: "厂牌",
        dataField: "",
      },
      {
        caption: "采用量",
        dataField: "adoption",
      },
      {
        caption: "剂量单位",
        dataField: "dosageName",
      },
      {
        type: "buttons",
        visible: false,
      },
    ],
    editing: {
      allowAdding: false,
      allowDeleting: false,
      allowUpdating: false,
      mode: "popup",
    },
    export: {
      enabled: true,
      allowExportSelectedData: true,
      fileName: componentInfo.title + new Date(),
    },
    onEditingStart(item) {
      formData = item.data;
    },
  } as dxDataGridOptions;
};

@Options({
  components: {
    DxDataGrid,
    DxColumn,
    DxPaging,
    DxEditing,
    DxPopup,
    DxLookup,
    DxForm,
    DxSearchPanel,
    DxExport,
    DxSorting,
    DxPager,
    DxRequiredRule,
    DxEmailRule,
    DxPatternRule,
    DxAsyncRule,
    DxSelection,
    ImageUpload,
    DxHtmlEditor,
    Pagination,
    DxTextBox,
    DxButton,
    DxSortable,
    Tree,
    DxTabs,
    CreateDrugMade,
    DataGrid,
  },
})
export default class DrugAgree extends Vue {
  @Inject()
  apiTool: ApiTool;
  importFile: any = {};
  formData: any = {
    page: {
      pageSize: 10,
    },
  };
  drugData: DrugData;
  selectedRowKeys = [];
  // 目录id
  get drugSortId() {
    return (this.$route.query.drugSortId || "") as string;
  }
  // 方案id
  get drugSchemeId() {
    return (this.$route.query.drugSchemeId || "") as string;
  }
  // 父目录id
  get parentId() {
    return (this.$route.query.parentId || "") as string;
  }
  // 药品id
  get drugId() {
    return (this.$route.query.drugId || "") as string;
  }
  // 药品id
  get specificationId() {
    return (this.$route.query.specificationId || "") as string;
  }
  // 药品id
  get drugType(): number {
    let type = Tool.convertToNumber(
      (this.$route.query.drugType || "") as string
    );
    return type;
  }
  pageInfo: PageInfo = {
    count: 0,
    pageSize: 10,
    index: 0,
  };
  searchByURL: SearchByURL;
  openTab = 0;
  isImport = false;
  solutionId = "";
  catalogId = "";
  catalogName = "";
  displayId = "";
  isEditHeader: Array<boolean> = [];
  headerNameList: Map<string, DictionaryFieldOutput> = new Map();
  @Inject()
  rightContextOption: RightContextI;
  isCreateDrug = false;
  editDrugId = ""; // 编辑药品id
  rightMenu = [
    {
      id: "edit",
      text: "编辑",
    },
  ];
  // 底层参数变化
  get listParams() {
    return (
      this.drugSchemeId +
      this.parentId +
      this.drugSortId +
      this.drugId +
      this.specificationId
    );
  }
  @Watch("listParams")
  watchQuery() {
    this.pageInfo.index = 0;
    this.pageInfo.count = 0;
    this.getList().then(() => {
      if (this.items.length > 0) {
        this.selectedRowKeys = [this.getFirstItem(this.items)[keyExpr]];
      }
    });
  }

  DataGridSetting = getDataGridSetting.call(this);

  // 获取第一项数据
  getFirstItem(list: any[]) {
    return list[0];
  }
  // 从url上获取参数
  getUrlquery(newVal: any) {
    this.pageInfo.index = 0;
    this.isEditHeader = [];
    this.solutionId = (newVal.solutionId || "").toString();
    this.catalogId = (newVal.catalogId || "").toString();
    this.catalogName = Tool.convertToString(newVal["name"]);
    this.displayId = Tool.convertToString(newVal["displayId"]);
    this.pageInfo.index = Tool.convertToNumber((newVal.page || "").toString());
  }
  setRightMenu(e) {
    this.rightContextOption.content = {
      event: e,
      id: "drugMade",
    };
    // 是否可修改
    // let row = e.row;
    // this.rightMenu[1]["disabled"] = !row;
    this.rightContextOption.items = this.rightMenu;
  }
  rightClick(event: CustomEvent) {
    let { detail = {} } = event;
    let { itemData, content } = detail;
    if (content.id != "drugMade") {
      return;
    }
    let row: any;
    switch (itemData.id) {
      case "edit":
        if (!this.specificationId) {
          notify("请先添加规格");
          return;
        }
        this.isCreateDrug = true;
        break;
      case "remove":
        row = content.event.row;
        this.drugData.delete(row.key).then(() => {
          this.getList();
        });
        break;
      default:
        break;
    }
  }
  addSuccess() {
    this.getList();
  }
  beforeUnmount() {
    document.removeEventListener("rightContext", this.rightClick);
  }
  async mounted() {
    document.addEventListener("rightContext", this.rightClick);
    this.searchByURL = new SearchByURL(this.$router, 0);
    let client = this.apiTool.createClient(DrugClient);
    this.drugData = new DrugData(client, this);
    this.getList();
  }

  // 自制药品列表
  items: OutputAgreementDrugModel[] = [];
  async getList() {
    if (!this.specificationId) {
      this.items = [];
      return;
    }
    let client = this.apiTool.createClient(SelfMadeDrugClient);
    let result = await client.getListPageSelfMadeDrug({
      specificationId: this.specificationId,
      pageInfo: {
        index: 0,
        pageSize: 100,
      },
    });
    this.items = result.listData;
  }

  setPageToUtl() {
    this.searchByURL.setParamsToUrl({ page: this.pageInfo.index });
  }

  // 获取表格标题
  getHeaderTitle(column, headerNameList = this.headerNameList): string {
    let dataField = column.column.dataField.replace("v", "V");
    let caption = column.column.caption;
    let title = headerNameList.get(dataField);
    return title ? title.name : caption;
  }
  // 获取上传文件
  getFile(file) {
    this.importFile = file;
  }
  // 提交
  uploadXlsx() {
    let client = this.apiTool.createClient(CatalogClient);
    let catalogId = this.catalogId;
    let solutionId = this.solutionId;
    let tempFileInfo = this.importFile[0];
    if (!catalogId) {
      notify("请选择需要导入数据的目录");
      return;
    }
    ViewTool.showLoading(true, this);
    client
      .importCatalog({
        catalogId,
        solutionId,
        tempFileInfo,
      })
      .then((result) => {
        if (result.isSuccess) {
          notify("导入完成", "success", 2000);
          setTimeout(() => {
            this.refresh();
          }, 1000);
        } else {
          notify(result.message, "error", 2000);
        }
        ViewTool.showLoading(false, this);
      })
      .catch((e) => {
        notify("系统异常", "error", 2000);
        ViewTool.showLoading(false, this);
      });
  }
  // 页面刷新
  refresh() {
    this.$router.replace({ path: "/refresh" });
  }
}
</script>

<style scoped lang="scss">
.grup-body {
  display: flex;
  justify-content: space-evenly;
}
.header-input {
  input {
    padding: 0 !important;
  }
}
</style>
